package io.github.eric.urpc.standalone.server;

import io.github.eric.urpc.core.conn.Connection;
import io.github.eric.urpc.core.rpc.Message;
import io.github.eric.urpc.server.ServerContext;
import io.github.eric.urpc.standalone.common.msg.IMMessage;
import io.github.eric.urpc.standalone.common.msg.IMMessageResult;
import io.github.eric.urpc.standalone.common.MessageStatus;

import java.util.Collection;
import java.util.function.Predicate;

import static io.github.eric.urpc.standalone.server.Application.SERVER;

public class ChatManager {
    private static ChatManager Instance;

    static {
        Instance = new ChatManager();
    }

    public static ChatManager getInstance() {
        return Instance;
    }

    public void sendAsync(Message message, String userId) {
        Collection<Connection> connections = ((ServerContext)SERVER.getServerConfig()).getConnectionManager().getConnections(new Predicate<Connection>() {
            @Override
            public boolean test(Connection connection) {
                Object obj = connection.getAttribute("UserId");
                return obj != null && obj.toString().equals(userId);
            }
        });
        if (connections.isEmpty()) {
            return;
        }
        Connection conn = connections.iterator().next();
        conn.sendAsync(message);
    }

    public IMMessageResult sendMessage(IMMessage imMessage) {
        IMMessageResult result = new IMMessageResult();
        result.setMessageId(imMessage.getMessageId());
        User user = UserManager.getInstance().get(imMessage.getToUserId());
        if (user == null) {
            result.setMessageStatus(MessageStatus.SEND_FAILED);
            return result;
        }
        result.setMessageStatus(MessageStatus.SEND_SUCCEED);
        sendAsync(imMessage, user.getId());
        return result;
    }

    public void relayIMMessageResult(IMMessageResult imMessageResult) {
        User user = UserManager.getInstance().get(imMessageResult.getFromUserId());
        if (user == null) {
            return;
        }
        SERVER.sendAsync(imMessageResult, connection -> {
            Object obj = connection.getAttribute(UserManager.USER_ID);
            return obj != null && obj.toString().equals(user.getId());
        });
    }
}
